package com.banzhi.shop.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CommonHeadAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.Management.Management_Data;

import com.banzhi.shop.entity.OnekeyShelf.OnekeyShelf;
import com.banzhi.shop.entity.OnekeyShelf.OnekeyShelfCallBack;
import com.banzhi.shop.entity.OnekeyShelf.OnekeyShelfImpl;
import com.banzhi.shop.entity.WXshare;
import com.banzhi.shop.model.CallBack.ManagementCallBack;
import com.banzhi.shop.model.CallBack.WXshareCallBack;
import com.banzhi.shop.model.IManagementModel;
import com.banzhi.shop.model.Impl.ManagementImpl;

import com.banzhi.shop.model.Impl.WXshareImpl;
import com.banzhi.shop.model.WXshareModel;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.CustomToast;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ShareUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 店铺管理
 */
public class CommodityManagementActivity extends BaseActivity implements View.OnClickListener, ManagementCallBack, SwipeRefreshLayout.OnRefreshListener, WXshareCallBack, OnekeyShelfCallBack {
    /**
     * 退出
     */
    private ImageView ivback;

    /**
     * 获取列表信息的实体类集合
     */
    private List<Management_Data> magData = new ArrayList<>();

    //一键上架数据的实体类集合
    private List<OnekeyShelf> onekeyData = new ArrayList<>();
    private OnekeyShelf onekeyShelf_data;

    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout srlayout;

    /**
     * adapte传过来的positon   用于删除集合你对应的商品
     */
    private int position;
    private RelativeLayout rlnodata;
    /**
     * 用于存储该商品的
     */
    private String wxURL;
    private static final int PENGYOUQUAN = 1;
    private static final int WEIXINHAOYOU = 2;
    private static final int LIANJIE = 3;
    private static final int ERWEIMA = 4;
    private WXshareModel wxmodel;
    private IManagementModel model;
    private EditText et_shousuo;
    private ImageView ivmanage;
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private CommonHeadAdapter<Management_Data> adapter;
    private int page = 1;
    private ImageView mIvShangjia;
    private PopupWindow mPopupWindow;
    private TextView mTvCancel;
    private TextView mTvTrue;
    private OnekeyShelfImpl mOnekeyModel;

    private TextView mTvNoData;
   // private TextView mTvMoreData;
    // private DynamicReceiver mDynamicReceiver;
    //private List<Goods_Data> datas = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_management);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        model = new ManagementImpl();
        wxmodel = new WXshareImpl();
        //一键上架
        mOnekeyModel = new OnekeyShelfImpl();


    }

    @Override
    protected void onStart() {
        super.onStart();
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getData(page, this);

    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        et_shousuo = (EditText) findViewById(R.id.et_shousuo);
        srlayout = (SwipeRefreshLayout) findViewById(R.id.srlayout);
        srlayout.setColorSchemeResources(R.color.themeColor);
        srlayout.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        srlayout.setOnRefreshListener(this);
        rlnodata = (RelativeLayout) findViewById(R.id.rl_nodata);
        mTvNoData = (TextView) findViewById(R.id.tv_nodata);
     //   mTvMoreData = (TextView) findViewById(R.id.tv_moredata);
        ivmanage = (ImageView) findViewById(R.id.iv_management);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);

        mIvShangjia = (ImageView) findViewById(R.id.iv_shangjia);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        ivmanage.setOnClickListener(this);

        mIvShangjia.setOnClickListener(this);

        et_shousuo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    model.getData(et_shousuo.getText().toString().trim(), CommodityManagementActivity.this);
                } else {
                    model.getData(CommodityManagementActivity.this);
                }
            }
        });
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                page++;
                LoadingDialogUtils.showProgress(CommodityManagementActivity.this, "正在加载,请稍后~");
                model.getData(page, CommodityManagementActivity.this);

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_management:
                Intent intent = new Intent(this, GoodsPaixuActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_shangjia:
                showOnekeyShelfPopupWindow(view);
                break;

        }
    }

    //一键上架所有商品
    private void showOnekeyShelfPopupWindow(View view) {
        View contentView = LayoutInflater.from(CommodityManagementActivity.this).inflate(R.layout.popumwindow_onekey_shelf, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LoadingDialogUtils.showProgress(CommodityManagementActivity.this, "正在上架,请稍后~");
                //一件上架的点击事件
                mOnekeyModel.getData(CommodityManagementActivity.this);

                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(CommodityManagementActivity.this).inflate(R.layout.activity_commodity_details, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 展示列表数据
     */
    private void showView() {
        if (adapter == null) {
            adapter = new CommonHeadAdapter<Management_Data>(this, R.layout.items_management_sku, magData) {
                @Override
                public void convert(ViewHolder holder, final Management_Data data, final int position) {

                    holder.setText(R.id.tv_title, data.getTitle());
                    if (ASUtils.isCanUse(data.getMarketprice())) {
                        holder.setText(R.id.tv_price, NumberUtils.DecimalFormat(data.getMarketprice()));
                    }
                    holder.setText(R.id.tv_zhuan, data.getProfit());
                    holder.setText(R.id.tv_kucun, data.getTotal());
                    if (ASUtils.isCanUse(data.getThumb())) {
                        Picasso.with(MyApp.context).load(data.getThumb()).placeholder(R.mipmap.zhanweitu2).into(holder.getImageView(R.id.iv_image));
                    }

                    holder.getImageView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            LoadingDialogUtils.showProgress(CommodityManagementActivity.this, "正在加载,请稍后~");
                            model.deleteGoods(data.getId(), null, CommodityManagementActivity.this);
                            CommodityManagementActivity.this.position = position;
                        }
                    });
                    holder.getImageView(R.id.iv_saveimages).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if ("1".equals(data.getIsregistergoods())) {
                                ToastUtils.makeToastShort("该商品为注册商品");
                            } else if ("0".equals(data.getStatus())) {
                                ToastUtils.makeToastShort("该商品已下架");
                            } else if ("1".equals(data.getDeleted())) {
                                ToastUtils.makeToastShort("该商品已删除");
                            } else {
                                Intent intent = new Intent(CommodityManagementActivity.this, CommodityDetailsActivity.class);
                                intent.putExtra("id", data.getId());
                                intent.putExtra("type", "1");
                                startActivity(intent);
                            }
                        }
                    });
                    holder.getImageView(R.id.iv_share).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if ("1".equals(data.getIsregistergoods())) {
                                ToastUtils.makeToastShort("该商品为注册商品");
                            } else if ("0".equals(data.getStatus())) {
                                ToastUtils.makeToastShort("该商品已下架");
                            } else if ("1".equals(data.getDeleted())) {
                                ToastUtils.makeToastShort("该商品已删除");
                            } else {
                                wxURL = null;
                                showSharePopupwindow(data);
                                CommodityManagementActivity.this.position = position;

                            }
                        }
                    });

                }

                @Override
                public void headconvert(HeaderViewHolder holder) {

                }
            };
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.setOnItemClickListener(new CommonHeadAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if ("1".equals(magData.get(position).getIsregistergoods())) {
                    ToastUtils.makeToastShort("该商品为注册商品");
                } else if ("0".equals(magData.get(position).getStatus())) {
                    ToastUtils.makeToastShort("该商品已下架");
                } else if ("1".equals(magData.get(position).getDeleted())) {
                    ToastUtils.makeToastShort("该商品已删除");
                } else {
                    Intent intent = new Intent(CommodityManagementActivity.this, CommodityDetailsActivity.class);
                    intent.putExtra("id", magData.get(position).getId());
                    startActivity(intent);
                }
            }
        });
    }


    /**
     * @param object 获取单品数据成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        if (srlayout.isRefreshing()) {
            srlayout.setRefreshing(false);
        }

        if (page == 1) {
            magData.clear();
        } else {
            if (((List<Management_Data>) object).size() == 0) {
                return;
            }
        }
        magData.addAll((List<Management_Data>) object);
        if (magData.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }

        showView();
        LoadingDialogUtils.dismiss();
    }

    /**
     * @param object 获取单品数据失败
     */
    @Override
    public void ongetDataError(Object object) {
        if (srlayout.isRefreshing()) {
            srlayout.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(CommodityManagementActivity.this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void deleteGoodsSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(this, "下架成功", jsonObject.optString("res"));

        magData.remove(position);

        if (magData.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void deleteGoodsError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onRefresh() {
        page = 1;
        if (et_shousuo.getText().length() == 0) {
            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
            model.getData(page, this);
        } else {
            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
            model.getData(page, et_shousuo.getText().toString().trim(), CommodityManagementActivity.this);
        }

    }

    @Override
    public void ongetWXdataSuccess(Object object, int num) {
        LoadingDialogUtils.dismiss();
        WXshare share = (WXshare) object;
        wxURL = share.getRes();
        if (num == LIANJIE) {
            ShareUtils.copyLianjie(this, wxURL);
        } else if (num == ERWEIMA) {
            ShareUtils.ereima3(this, magData.get(position).getTitle(), magData.get(position).getMarketprice(), null, null, null, magData.get(position).getThumb(), wxURL);
        } else if (num == WEIXINHAOYOU) {
            ShareUtils.wxshare(magData.get(position).getTitle(), magData.get(position).getThumb(), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
        } else if (num == PENGYOUQUAN) {
            ShareUtils.wxPengyouquan(magData.get(position).getTitle(), magData.get(position).getThumb(), wxURL);
        }
    }

    @Override
    public void ongetWXdataError(Object object, int num) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * 展示分享的popupwindow
     */
    private void showSharePopupwindow(final Management_Data data) {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_share_goods, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        TextView tvprice = (TextView) contentView.findViewById(R.id.tvmoney);
        TextView tvpricetwo = (TextView) contentView.findViewById(R.id.tv_money_two);
        LinearLayout llpengyouquan = (LinearLayout) contentView.findViewById(R.id.ll_pengyouquan);
        LinearLayout llweixin = (LinearLayout) contentView.findViewById(R.id.ll_weixing);
        LinearLayout lllianjie = (LinearLayout) contentView.findViewById(R.id.ll_lianjie);
        LinearLayout llerweima = (LinearLayout) contentView.findViewById(R.id.ll_erweima);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (data != null) {
            tvprice.setText(NumberUtils.DecimalFormat(data.getProfit()));
            tvpricetwo.setText(NumberUtils.DecimalFormat(data.getProfit()));
            lllianjie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(CommodityManagementActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, LIANJIE, CommodityManagementActivity.this);
                    } else {
                        ShareUtils.copyLianjie(CommodityManagementActivity.this, wxURL);
                    }
                }
            });
            llerweima.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(CommodityManagementActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, ERWEIMA, CommodityManagementActivity.this);
                    } else {
                        ShareUtils.ereima3(CommodityManagementActivity.this, data.getTitle(), data.getMarketprice(), null, null, null, data.getThumb(), wxURL);
                    }
                }
            });
            llweixin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(CommodityManagementActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, WEIXINHAOYOU, CommodityManagementActivity.this);
                    } else {
                        ShareUtils.wxshare(data.getTitle(), data.getThumb(), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
                    }
                }
            });
            llpengyouquan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(CommodityManagementActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, PENGYOUQUAN, CommodityManagementActivity.this);
                    } else {
                        ShareUtils.wxPengyouquan(data.getTitle(), data.getThumb(), wxURL);
                    }
                }
            });
        }
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxURL = null;
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    @Override
    public void onGetOnekeyShelfDataSuccess(Object object) {
        //  LogUtils.d("onGetOnekeyShelfDataSuccess",object.toString());

      //  srlayout.setRefreshing(false);
        if (srlayout.isRefreshing()) {
            srlayout.setRefreshing(false);
        }
        LoadingDialogUtils.showProgress(CommodityManagementActivity.this, "正在刷新,请稍后~");
        page = 1;
        model.getData(page, CommodityManagementActivity.this);



        if (magData.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        LoadingDialogUtils.dismiss();


    }

    @Override
    public void onGetOnekeyShelfDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }
}
